﻿using System.Reflection;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.Web;
using ViewServices;
using WebEngine.App_Start;

namespace WebEngine
{
    public class MvcApplication : System.Web.HttpApplication, IContainerProviderAccessor
    {
        private static IContainerProvider _containerProvider;

        public IContainerProvider ContainerProvider
        {
            get { return _containerProvider; }
        }

        protected void Application_Start()
        {
            ViewServicesDatabase.Initialize();

            var builder = new ContainerBuilder();
            builder.RegisterModule<ViewServicesModule>();
            builder.RegisterSource(new ViewRegistrationSource());
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            var container = builder.Build();
            _containerProvider = new ContainerProvider(container);
            ControllerBuilder.Current.SetControllerFactory(new ControllerFactory(ContainerProvider));
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
    }
}
